import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/article_provider.dart';
import '../providers/audio_provider.dart';
import '../models/content.dart';
import '../services/api_service.dart';
import '../widgets/audio_player_widget.dart';
import '../widgets/highlight_text.dart';
import '../config/app_theme.dart';

/// 文章详情页
class ArticleDetailScreen extends StatefulWidget {
  final int articleId;

  const ArticleDetailScreen({super.key, required this.articleId});

  @override
  State<ArticleDetailScreen> createState() => _ArticleDetailScreenState();
}

class _ArticleDetailScreenState extends State<ArticleDetailScreen> {
  final ApiService _apiService = ApiService();
  String _currentLanguage = 'cn';
  Content? _content;
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  Future<void> _loadData() async {
    setState(() => _loading = true);
    
    final articleProvider = Provider.of<ArticleProvider>(context, listen: false);
    final audioProvider = Provider.of<AudioProvider>(context, listen: false);
    
    try {
      // 如果是当前正在播放的文章，同步语言状态
      if (audioProvider.currentArticle?.articleId == widget.articleId) {
        _currentLanguage = audioProvider.currentLanguage;
        debugPrint('同步语言状态: $_currentLanguage');
      }
      
      // 加载文章详情
      await articleProvider.fetchArticleDetail(widget.articleId);
      
      // 检查收藏状态
      try {
        final isFavorite = await articleProvider.checkFavorite(widget.articleId);
        if (articleProvider.currentArticle != null) {
          articleProvider.currentArticle!.isFavorite = isFavorite;
        }
      } catch (e) {
        debugPrint('检查收藏状态失败: $e');
      }
      
      // 加载内容
      await _loadContent();
      
      // 如果不是当前正在播放的文章，则初始化音频
      if (audioProvider.currentArticle?.articleId != widget.articleId) {
        await audioProvider.initAudio(
          widget.articleId,
          articleProvider.currentArticle!,
          _currentLanguage,
        );
      }
    } catch (e) {
      debugPrint('加载失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载失败: $e')),
        );
      }
    } finally {
      if (mounted) {
        setState(() => _loading = false);
      }
    }
  }

  Future<void> _loadContent() async {
    try {
      final response = await _apiService.getArticleContent(
        widget.articleId,
        _currentLanguage,
      );
      setState(() {
        _content = Content.fromJson(response.data['data']);
      });
    } catch (e) {
      debugPrint('加载内容失败: $e');
      // 使用降级方案
      final articleProvider = Provider.of<ArticleProvider>(context, listen: false);
      setState(() {
        _content = Content(
          contentId: widget.articleId,
          articleId: widget.articleId,
          language: _currentLanguage,
          summary: articleProvider.currentArticle?.content ?? '暂无内容',
          sentences: [
            Sentence(
              index: 0,
              text: articleProvider.currentArticle?.content ?? '暂无内容',
            ),
          ],
        );
      });
    }
  }

  Future<void> _switchLanguage(String language) async {
    if (_currentLanguage == language) return;
    
    setState(() {
      _currentLanguage = language;
      _loading = true;
    });
    
    final audioProvider = Provider.of<AudioProvider>(context, listen: false);
    
    try {
      await _loadContent();
      await audioProvider.switchLanguage(language, widget.articleId);
    } catch (e) {
      debugPrint('切换语言失败: $e');
    } finally {
      setState(() => _loading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _loading
          ? const Center(child: CircularProgressIndicator())
          : Consumer2<ArticleProvider, AudioProvider>(
              builder: (context, articleProvider, audioProvider, child) {
                final article = articleProvider.currentArticle;
                if (article == null) {
                  return const Center(child: Text('文章不存在'));
                }

                return Container(
                  decoration: const BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: [
                        Color(0xFF0E3A5B), // 顶部蓝色
                        AppTheme.bgDark,  // 底部深色
                      ],
                    ),
                  ),
                  child: Stack(
                    children: [
                      CustomScrollView(
                        slivers: [
                          // AppBar
                          SliverAppBar(
                            backgroundColor: Colors.transparent,
                            elevation: 0,
                            title: Text(
                              article.title,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                            centerTitle: true,
                            pinned: true,
                            actions: [
                              Consumer<ArticleProvider>(
                                builder: (context, ap, _) => IconButton(
                                  icon: Icon(
                                    article.isFavorite == true ? Icons.star : Icons.star_border,
                                    color: article.isFavorite == true ? Colors.orange : null,
                                  ),
                                  onPressed: () async {
                                    await ap.toggleFavorite(article.articleId);
                                  },
                                ),
                              ),
                            ],
                          ),
                          
                          // 内容
                          SliverToBoxAdapter(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                // 文章头部
                                Padding(
                                  padding: const EdgeInsets.all(20),
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    children: [
                                      // 标题上方的小图标
                                      Image.asset(
                                        'assets/images/titleP.png',
                                        width: 40,
                                        height: 40,
                                      ),
                                      const SizedBox(height: 8),
                                      // 标题 - 居中显示，支持多行但不溢出
                                      Center(
                                        child: Text(
                                          article.title,
                                          textAlign: TextAlign.center,
                                          style: const TextStyle(
                                            fontSize: 22,
                                            fontWeight: FontWeight.bold,
                                            color: AppTheme.textPrimary,
                                            height: 1.4,
                                          ),
                                          maxLines: 3,
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ),
                                      const SizedBox(height: 12),
                                      // 资讯信息行（按需求隐藏）
                                      const SizedBox.shrink(),
                                      // URL（如果有）
                                      if (article.url != null && article.url!.isNotEmpty) ...[
                                        const SizedBox(height: 8),
                                        Text(
                                          article.url!,
                                          style: TextStyle(
                                            color: AppTheme.textTertiary.withOpacity(0.6),
                                            fontSize: 11,
                                          ),
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ],
                                    ],
                                  ),
                                ),
                                
                                // 摘要（按需求暂时隐藏）
                                if (false && _content?.summary != null)
                                  const SizedBox.shrink(),
                                
                                // 会议内容（原“正文”）
                                if (_content?.sentences != null)
                                  Padding(
                                    padding: const EdgeInsets.symmetric(horizontal: 0),
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Padding(
                                          padding: const EdgeInsets.symmetric(horizontal: 16),
                                          child: Row(
                                            mainAxisAlignment: MainAxisAlignment.start,
                                            children: [
                                              const Text(
                                                '会议内容',
                                                style: TextStyle(
                                                  fontSize: 16,
                                                  fontWeight: FontWeight.w600,
                                                  color: AppTheme.textPrimary,
                                                ),
                                              ),
                                              const SizedBox(width: 6),
                                              Image.asset(
                                                'assets/images/stars.png',
                                                width: 18,
                                                height: 18,
                                              ),
                                            ],
                                          ),
                                        ),
                                        const SizedBox(height: 12),
                                        HighlightText(sentences: _content!.sentences!),
                                      ],
                                    ),
                                  ),
                                
                                // 底部留空给播放器
                                const SizedBox(height: 240),
                              ],
                            ),
                          ),
                        ],
                      ),
                      
                      // 底部播放器
                      const Positioned(
                        left: 0,
                        right: 0,
                        bottom: 0,
                        child: AudioPlayerWidget(),
                      ),
                      
                      // 固定在播放器上方的语言切换
                      Positioned(
                        left: 0,
                        right: 0,
                        bottom: 200,
                        child: _buildLanguageSwitcher(),
                      ),
                    ],
                  ),
                );
              },
            ),
    );
  }

  Widget _buildLanguageSwitcher() {
    return Container(
      height: 60,
      alignment: Alignment.center,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          _buildLanguageButton('cn', '中文'),
          const SizedBox(width: 16),
          _buildLanguageButton('en', '原文'),
        ],
      ),
    );
  }

  Widget _buildLanguageButton(String language, String label) {
    final isSelected = _currentLanguage == language;
    
    return GestureDetector(
      onTap: () => _switchLanguage(language),
      child: Container(
        width: 120,
        padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 40),
        decoration: BoxDecoration(
          color: isSelected 
              ? null 
              : const Color(0xFF1C1C1E).withOpacity(0.8),
          gradient: isSelected ? AppTheme.primaryGradient : null,
          borderRadius: BorderRadius.circular(25),
          border: Border.all(
            color: isSelected ? Colors.transparent : AppTheme.borderColor,
          ),
          boxShadow: isSelected
              ? [
                  BoxShadow(
                    color: AppTheme.accentColor.withOpacity(0.5),
                    blurRadius: 20,
                    spreadRadius: 0,
                  ),
                ]
              : null,
        ),
        child: Text(
          label,
          textAlign: TextAlign.center,
          style: TextStyle(
            color: isSelected ? Colors.white : AppTheme.textSecondary,
            fontSize: 15,
            fontWeight: isSelected ? FontWeight.w600 : FontWeight.w500,
          ),
        ),
      ),
    );
  }
}

